package com.sikao.app.ui;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sikao.app.R;
import com.sikao.app.ui.base.BaseActivity;
import com.sikao.app.utils.FileUtils;
import com.sikao.app.utils.PermissionUtils;

import java.io.File;

import static com.sikao.app.utils.PermissionUtils.MY_PERMISSIONS_REQUEST_CALL_PHONE;

public class SelectPictureActivity extends BaseActivity implements View.OnClickListener {

	public static final int REQUEST_CODE_CAMERA = 18;
	public static final int REQUEST_CODE_LOCAL = 19;
	private String picturePath;//图片路径
	private File cameraFile;//调取相机时图片保存位置
	private RelativeLayout rl;
	private TextView takePictureTv;
	private TextView pictureFileTv;
	private TextView cancleTv;
	private String type;
	private PermissionUtils permissionUtils;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_select_picture);
		super.onCreate(savedInstanceState);

	}

	@Override
	protected void initData() {

	}

	@Override
	protected void initView() {
		rl = (RelativeLayout) findViewById(R.id.rl);
		takePictureTv = (TextView) findViewById(R.id.take_picture_tv);
		pictureFileTv = (TextView) findViewById(R.id.picture_file_tv);
		cancleTv = (TextView) findViewById(R.id.cancle_tv);
	}

	@Override
	protected void initListener() {
		rl.setOnClickListener(this);
		takePictureTv.setOnClickListener(this);
		pictureFileTv.setOnClickListener(this);
		cancleTv.setOnClickListener(this);
	}

	@Override
	protected void init() {
		/*AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("选择图片");
		String[] types = {"拍照", "图库"};
		builder.setItems(types, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (which == 0) {
					selectPicFromCamera();
				} else {
					selectPicFromLocal();
				}
				dialog.dismiss();
			}
		});
		builder.setCancelable(false);
		dialog = builder.create();
		dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				dialog.dismiss();
				finish();
				return false;
			}
		});
		dialog.show();*/
	}

	/**
	 * 照相获取图片
	 */
	public void selectPicFromCamera() {
		if (!FileUtils.hasSDCard()) {
			Toast.makeText(SelectPictureActivity.this, ("SD卡不存在，不能拍照"), Toast.LENGTH_SHORT).show();
			return;
		}
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		// 指定调用相机拍照后照片的储存路径
		cameraFile = new File(FileUtils.imagePath, "photo" + System.currentTimeMillis() + ".jpg");
		cameraFile.getParentFile().mkdirs();
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));
		startActivityForResult(intent, REQUEST_CODE_CAMERA);
	}

	/**
	 * 从图库获取图片
	 */
	public void selectPicFromLocal() {
		Intent intent;
		if (Build.VERSION.SDK_INT < 19) {
			intent = new Intent(Intent.ACTION_GET_CONTENT);
			intent.setType("image/*");
		} else {
			intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			//intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
		}
		startActivityForResult(intent, REQUEST_CODE_LOCAL);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {

				case REQUEST_CODE_CAMERA: //相机照片
					if (cameraFile != null && cameraFile.exists()) {
						picturePath = cameraFile.getAbsolutePath();
					}
					Intent intent = getIntent();
					intent.putExtra("path", picturePath);
					setResult(RESULT_OK, intent);
					finish();
					break;
				case REQUEST_CODE_LOCAL: //本地相册图片
					if (data != null) {
						Uri selectedImage = data.getData();
						if (selectedImage != null) {
							picturePath = getPicByUri(selectedImage);
						}
					}
					Intent intent1 = getIntent();
					intent1.putExtra("path", picturePath);
					setResult(RESULT_OK, intent1);
					finish();
					break;
				default:
					break;
			}
		} else {
			finish();
		}

	}

	private String getPicByUri(Uri selectedImage) {
		Cursor cursor = this.getContentResolver().query(selectedImage, null, null, null, null);
		if (cursor != null) {
			cursor.moveToFirst();
			int columnIndex = cursor.getColumnIndex("_data");
			picturePath = cursor.getString(columnIndex);
			cursor.close();
			cursor = null;
			if (picturePath == null || picturePath.equals("null")) {
				Toast toast = Toast.makeText(SelectPictureActivity.this, "找不到图片", Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				return null;
			} else {
				return picturePath;
			}
		} else {
			File file = new File(selectedImage.getPath());
			if (!file.exists()) {
				Toast toast = Toast.makeText(SelectPictureActivity.this, "找不到图片", Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				return null;
			}
			picturePath = file.getAbsolutePath();
			return picturePath;
		}
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.rl:
				finish();
				break;
			case R.id.take_picture_tv:
				type = "1";
				if (permissionUtils == null) {
					permissionUtils = new PermissionUtils(this);
				}
				if (!permissionUtils.needPermission1(100)) {
					selectPicFromCamera();
				}
				break;
			case R.id.picture_file_tv:
				type = "2";
				if (permissionUtils == null) {
					permissionUtils = new PermissionUtils(this);
				}
				if (!permissionUtils.needPermission2(200)) {
					selectPicFromLocal();
				}
				break;
			case R.id.cancle_tv:
				type = "0";
				finish();
				break;
			default:
				break;
		}
	}

	@Override
	public void finish() {
		super.finish();
		overridePendingTransition(R.anim.bottom_push_in, R.anim.bottom_push_out);
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

		if (requestCode == 100) {
			if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
				selectPicFromCamera();
			} else {
				// Permission Denied
				finish();
			}
		}


		if (requestCode == 200) {
			if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
				selectPicFromLocal();
			} else {
				// Permission Denied
				finish();
			}
		}
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
	}

	private boolean requestStoragePermission() {
		//第二个参数是需要申请的权限
		if (ContextCompat.checkSelfPermission(this,
				Manifest.permission.WRITE_EXTERNAL_STORAGE)
				!= PackageManager.PERMISSION_GRANTED) {

			//权限还没有授予，需要在这里写申请权限的代码
		} else {
			//权限已经被授予，在这里直接写要执行的相应方法即可
		}
		return true;
	}

	private boolean requestCameraPermission() {
		//第二个参数是需要申请的权限
		if (ContextCompat.checkSelfPermission(this,
				Manifest.permission.CAMERA)
				!= PackageManager.PERMISSION_GRANTED) {
			ActivityCompat.requestPermissions(this,
					new String[]{Manifest.permission.CAMERA},
					MY_PERMISSIONS_REQUEST_CALL_PHONE);

			//权限还没有授予，需要在这里写申请权限的代码
		} else {
			//权限已经被授予，在这里直接写要执行的相应方法即可
		}
		return true;
	}

}
